var initDatatable = (function () {

    var datatable = function () { };

    datatable.prototype = {
        init: function (eles, list_grids, first_page_data) {
            this._table = null; // datatable实例
            this._tableEle = $('#' + eles.tableId); // table 元素
            this._boxEle = $('#' + eles.boxId); // 容器元素
            this._list_grids = list_grids; // 后台配置的列表定义
            this._first_page_data = this._formatData(first_page_data); // 首页数据
            this._search = null; // 搜索框实例

            this.createTable();
            this._bindEvent();
            this._bindContextMenu();
            this._minWidth = 0;
            window.t = this._table;
        },

        //生成tables
        createTable: function () {
            var context = this;
            this._table = this._tableEle.DataTable({

                /************ Features ************/
                info: true, // 控制是否显示表格左下角的信息
                lengthChange: true, // 是否允许用户改变表格每页显示的记录数
                ordering: true, // 是否允许Datatables开启排序
                paging: true, // 是否开启本地分页
                processing: true, // 是否显示处理状态(排序的时候，数据很多耗费时间长的话，也会显示这个)
                // scrollX: false, // 设置水平滚动
                // scrollY: false, // 设置垂直滚动
                // searching:true, // 是否允许Datatables开启本地搜索
                serverSide: true, // 是否开启服务器模式
                stateSave: true, // 保存状态 - 在页面重新加载的时候恢复状态（页码等内容）
                autoWidth: false, // 控制Datatables是否自适应宽度
                deferRender: false, // 控制Datatables的延迟渲染，可以提高初始化的速度

                /************ settings ************/
                language: {
                    "sInfoEmpty": "共 0 条",
                },
                lengthMenu: [10, 20, 50, 100],
                pageLength: (document.body.clientHeight >= 700 ? 20 : 10), // 大屏幕默认显示20条, 小屏幕默认显示10条
                order: this._defaultOrder(), // 默认按照第一列(id)降序排序
                dom: "<'row'<'col-sm-12'<'table-box' tr>>>" +
                "<'row datatable-footer'<'col-sm-6'li><'col-sm-6'p>>",
                renderer: 'bootstrap',

                ajax: {
                    url: "",
                    data: {
                        fromDataTable: 1
                    },
                    type: "post",
                    dataSrc: function (json) {
                        return context._formatData(json.data);
                    }
                },
                data: this._first_page_data,

                /************ columns ************/
                columnDefs: [{
                    "targets": "_all",
                    "createdCell": function (td, cellData, rowData, row, col) {
                        if (!$(td).hasClass("cell_checkbox")) {
                            $(td).attr('title', $("<div>" + cellData + "</div>").text()).html("<div class='cellTd'>" + cellData + "</div>");
                        }
                    }
                }],
                columns: this._parseColumnSetting(),
                fixedColumns: {
                    leftColumns: 5,
                    rightColumns: 5,
                },

                /************ callback ************/
                drawCallback: function () {
                    context._drawCallback();
                },

                initComplete: function (settings, json) {
                    context._InitComplete();
                },

                stateSaveCallback: function (settings, data) {
                    localStorage.setItem('_DataTables_' + settings.sInstance, JSON.stringify(data));
                },

                stateLoadCallback: function (settings) {
                    return JSON.parse(localStorage.getItem('_DataTables_' + settings.sInstance));
                }
            });
        },

        // 默认排序
        _defaultOrder: function () {
            var order = [
                [1, 'desc']
            ];
            for (var i = 0; i < this._list_grids.length; i++) {
                if (this._list_grids[i].orderdir) {
                    order = [
                        [i + 1, this._list_grids[i].orderdir == 'asc' ? 'asc' : 'desc']
                    ];
                    break;
                }
            }
            return order;
        },

        // 列配置解析 sortable  searchable等...
        _parseColumnSetting: function () {

            var columns = [];
            var column_item = {};
            var list_grids = this._list_grids;

            // 第一列插入复选框
            column_item['name'] = '';
            column_item['orderable'] = false;
            column_item['width'] = '18px';
            column_item['class'] = 'cell_checkbox';
            columns.push(column_item);

            var tmpwidth = 0, tmpcolwidth = 0;
            for (var i = 0; i < list_grids.length; i++) {
                column_item = {};
                column_item['name'] = list_grids[i].field[0];
                column_item['orderable'] = list_grids[i].sortable === true;
                column_item['width'] = list_grids[i]['width'] ? list_grids[i]['width'] : undefined;
                column_item['searchable'] = list_grids[i].searchable === true;
                if (column_item['fixed'] == '-1') {
                    column_item['visible'] = false;
                }
                columns.push(column_item);
            }
            return columns;
        },

        // 格式化数据, 第一列自动补全 checkbox
        _formatData: function (data) {
            for (var i = 0; i < data.length; i++) {
                data[i].unshift("<input class='ids checkbox' type='checkbox'  value='" + data[i][0] + "' name='ids[]'>");
            }
            return data;
        },

        _bindEvent: function () {
            var context = this;

            // 异步请求前
            this._tableEle.on('preXhr.dt', function (e, settings, data) { });

            // 异步请求完成
            this._tableEle.on('xhr.dt', function (e, settings, data) {
                // 检测后台会话是否已经过期
                if (data.logout === true) {
                    window.location.href = data.loginUrl;
                }
            });
        },

        _drawCallback: function () {
            var context = this;

            // iCheck 初始化，全选
            KCONE.isCheck.init(this._tableEle, true);

            // 表格宽度
            this._setWidth();

            // 设置底部填充表格的函数
            this._setFooter();
        },

        _InitComplete: function () {
            var context = this;

            // 默认隐藏第二列(ID)
            //this._table.state.loaded() || this._table.column(1).visible(false);

            // "新增/删除"等表头按钮绑定事件
            this._bindTableBtns();

            // 操作列按钮绑定事件
            this._bindOptBtns();

            // "设置"按钮,显示或者隐藏列
            _datatable_column_(this, this._table, this._boxEle, this._list_grids);

            // "搜索"按钮,显示或者隐藏搜索栏
            // _datatable_search_(this, this._table, this._boxEle, this._list_grids);

            // "搜索"按钮,使用工具栏布局
            this._search = _datatable_search_(this, this._table, this._boxEle, this._list_grids);

            //显示表格
            this._tableEle.removeClass('table-opacity').parents(".table-box").css('opacity', '1');

            // 检查强制显示的列是否被隐藏
            var columns = this._table.state().columns;
            for (var i = 1; i < columns.length; i++) {
                if (!columns[i].visible && this._list_grids[i - 1]['fixed']) {
                    this._table.column(i).visible(true);
                }
                if (this._list_grids[i - 1]['fixed'] == -1) {
                    this._table.column(i).visible(false);
                }
            }

            //刷新页面显示loading,datatable初始化后隐藏
            this._tableEle.parents('.table-wrap').find('.table-loading').hide();

            // check 高亮行
            var highLightTr = function(){
                var el = $(this);
                var tr = el.closest('tr');
                if(el.is(':checked')){
                    tr.addClass('tr-checked-highlight');
                }else{
                    tr.removeClass('tr-checked-highlight');
                }
            };
            this._tableEle.delegate('.ids.checkbox','ifClicked change',highLightTr);

            this._tableEle.delegate('tbody>tr','click',function(event){
                var el = $(event.target);
                var cb;
                if(!el.is('a')){
                    cb = el.closest('tr').find('.ids.checkbox');
                    if(cb.is(':checked')){
                        cb.iCheck('uncheck',true);
                    }else{
                        cb.iCheck('check',true);
                    }
                    highLightTr.apply(cb);
                }
            });
        },

        // 总列数在10列以内时表格定宽, 超过10列时显示横向滚动条
        _setWidth: function () {
            var list_grids = this._list_grids;
            var tmpwidth = 0, tmpcolwidth = 0;
            for (var i = 0; i < list_grids.length; i++) {
                if (this._table.column(i).visible() == false) {
                    continue;
                }
                tmpwidth = parseInt(list_grids[i]['width'] ? list_grids[i]['width'] : 0);
                tmpcolwidth += ((tmpwidth) ? tmpwidth : ((i == 0) ? 30 : 160));
            }
            this._minWidth = tmpcolwidth;
            var width = this._table.state().columns.length > 10 ? "auto" : "100%";
            this._tableEle.css('width', width);
            this._tableEle.css('min-width', (tmpcolwidth + 20 * list_grids.length) + 'px');

        },

        // 填充表格底部
        _setFooter: function () {
            var fullTable = this._tableEle.parents('.table-wrap').find("#table-full");
            var data = this._table.data();
            var trs = "";
            for (var i = 0; i < data.length; i++) {
                trs += "<tr>";
                for (var y = 0; y < data[i].length; y++) {
                    trs += "<td><span>" + data[i][y] + "</span></td>";
                }
                trs += "</tr>";
            }
            fullTable.children('tbody').html(trs);
            KCONE.isCheck.init(fullTable);
        },

        // 绑定表头按钮点击事件
        _bindTableBtns: function () {
            var context = this;
            this._tableEle.closest('.box').find('.dataTables_tool .btn._dt_btns_').click(function () {
                var el = $(this);
                var callback = el.attr('data-callback');
                var param = el.attr('data-param');

                if (callback) {
                    var jsCallback = '_datatable_' + callback;
                    window[jsCallback].call(el, context, context._table, param, {});
                    return false;
                }

                window.location.href = el.attr('data-href');
                return false;
            });
        },

        // 委托操作列按钮点击事件
        _bindOptBtns: function () {
            var context = this;
            this._tableEle.delegate('.dataTable_operator_btn', 'click', function () {
                var dataHref = $(this).attr('data-href');
                var dataAjax = parseInt($(this).attr('data-ajax'));
                var dataConfirm = parseInt($(this).attr('data-confirm'));
                var jsCallback = $(this).attr('data-callback');
                var jsParam = $(this).attr('data-param');
                var el = $(this);

                if (jsCallback) {
                    jsCallback = '_datatable_' + jsCallback;
                    var ptr = el.closest('tr');
                    var index = ptr.prevAll().length;
                    var _data = context._table.row(index).data();
                    var data = {};
                    for (var i = 0; i < context._list_grids.length; i++) {
                        data[context._list_grids[i]['field'][0]] = _data[i + 1];
                    }
                    window[jsCallback].call(el, context, context._table, jsParam, data);
                    return false;
                }
                return true;
            });
        },

        // 绑定右键菜单
        _bindContextMenu: function () {
            // 当前行
            var tr;
            var hightClass = 'context-menu-tr-hightlight';
            $.contextMenu({
                // 禁用动画, 提高响应速度
                animation: { duration: 0, show: 'show', hide: 'hide' },
                // 选择器
                selector: '#' + this._tableEle.attr('id') + '>tbody>tr',
                // 显示菜单时当前行高亮
                events: {
                    hide: function (options) {
                        tr.removeClass(hightClass);
                    }
                },
                // 动态创建菜单选项
                build: function ($trigger, e) {
                    var el = $(e.target);
                    tr = el.closest('tr');
                    var btns = tr.find('.dataTable_operator_btn');
                    var items = {};
                    var callback = function (key, options) {
                        btns.eq(key).click();
                    };
                    btns.each(function (i) {
                        var el = $(this);
                        items[i] = {
                            'name': el.text()
                        };
                    });
                    btns.length && tr.addClass(hightClass);
                    return {
                        callback: callback,
                        items: items
                    };
                }
            });
        }
    };

    return function (tableEle, list_grids, first_page_data) {
        var a = new datatable();
        a.init(tableEle, list_grids, first_page_data);
    };
})();
